﻿using Infrastructure;
using OpenAuth.App.ViewModel;
using OpenAuth.Domain;
using OpenAuth.Domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenAuth.App
{
    /// <summary>
    /// ⑥应用层内，组合仓储接口，定义对外公共方法
    /// 下面是定义表现层控制器视图js文件
    /// </summary>
    public class SortManagerApp
    {
        private ISortRepository _repository;
        private IUnitWork _unitWork;

        /// <summary>
        /// 此处的构造函数使用的autofac映射
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="unitWork"></param>
        public SortManagerApp(ISortRepository repository, IUnitWork unitWork)
        {
            this._repository = repository;
            this._unitWork = unitWork;
        }




        /// <summary>
        /// 获取单个类别
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Sort Find(Guid id)
        {
            var sort = _repository.FindSingle(u => u.Id == id);
            if (sort == null) return new Sort();

            return sort;
        }
        /// <summary>
        /// 获取当前组织的所有下级组织
        /// </summary>
        private Guid[] GetSubSorts(Guid sortId)
        {
            var sort = Find(sortId);
            var sorts = _repository.Find(u => u.CascadeId.Contains(sort.CascadeId)).Select(u => u.Id).ToArray();
            return sorts;
        }
        /// <summary>
        /// 获取总数
        /// </summary>
        /// <param name="sortId"></param>
        /// <returns></returns>
        public int GetSortCntInOrg(Guid sortId)
        {
            if (sortId == Guid.Empty)
            {
                return _repository.Find(null).Count();
            }
            else
            {
                return _repository.GetSortCntInSorts(GetSubSorts(sortId));
            }
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public List<Sort> LoadAll()
        {
            return _repository.Find(null, s => s.CascadeId).ToList();
        }


        /// <summary>
        /// 加载一个分类及子分类全部Sorts
        /// </summary>
        public GridData Load(Guid parentId, int pageindex, int pagesize)
        {
            IQueryable<Sort> sorts;
            int total = 0;
            if (parentId == Guid.Empty)
            {
                sorts = _unitWork.Find<Sort>(pageindex, pagesize);
                total = _repository.GetCount();
            }
            else
            {
                var ids = GetSubSorts(parentId);
                sorts = _unitWork.Find<Sort>(pageindex, pagesize, "SortNo", u => ids.Contains(u.Id));
                total = _repository.GetSortCntInSorts(ids);
            }

            var query = from c in sorts
                        join sort in _unitWork.Find<Sort>(null) on c.ParentId equals sort.Id into temp
                        from sort in temp.DefaultIfEmpty()
                        select new
                        {
                            c.CascadeId,
                            c.Name,
                            c.ParentId,
                            ParentName = string.IsNullOrEmpty(sort.Name) ? "根节点" : sort.Name,
                            c.SortNo,
                            c.Status,
                            c.Id
                        };
            return new GridData()
            {
                records = total,
                total = (int)Math.Ceiling((double)total / pagesize),
                rows = query.ToList().OrderBy(s => s.CascadeId),
                page = pageindex
            };
        }

        /// <summary>
        /// 删除单个或多个
        /// </summary>
        /// <param name="ids"></param>
        public void Delete(Guid[] ids)
        {
            _repository.Delete(u => ids.Contains(u.Id));
        }

        /// <summary>
        /// 增加或者更新
        /// </summary>
        /// <param name="model"></param>
        public void AddOrUpdate(Sort model)
        {
            Sort sort = new Sort();
            model.CopyTo(sort);
            ChangeModuleCascade(sort);

            if (sort.Id == Guid.Empty)
            {
                _repository.Add(sort);
            }
            else
            {
                //获取旧的的CascadeId
                var CascadeId = _repository.FindSingle(o => o.Id == sort.Id).CascadeId;
                //根据CascadeId查询子分类
                var subSorts = _repository.Find(u => u.CascadeId.Contains(CascadeId) && u.Id != sort.Id).OrderBy(u => u.CascadeId).ToList();

                _repository.Update(sort);

                //更新子分类的CascadeId
                foreach (var a in subSorts)
                {
                    ChangeModuleCascade(a);
                    _repository.Update(a);
                }
            }
        }


        #region 私有方法

        //修改对象的级联ID，生成类似XXX.XXX.X.XX
        private void ChangeModuleCascade(Sort sort)
        {
            string cascadeId;
            int currentCascadeId = 1;  //当前结点的级联节点最后一位
            var sameLevels = _repository.Find(o => o.ParentId == sort.ParentId && o.Id != sort.Id);
            foreach (var obj in sameLevels)
            {
                int objCascadeId = int.Parse(obj.CascadeId.TrimEnd('.').Split('.').Last());
                if (currentCascadeId <= objCascadeId) currentCascadeId = objCascadeId + 1;
            }

            if (sort.ParentId != null && sort.ParentId != Guid.Empty)
            {
                var parentOrg = _repository.FindSingle(o => o.Id == sort.ParentId);
                if (parentOrg != null)
                {
                    cascadeId = parentOrg.CascadeId + currentCascadeId + ".";
                }
                else
                {
                    throw new Exception("未能找到该组织的父节点信息");
                }
            }
            else
            {
                cascadeId = ".0." + currentCascadeId + ".";
                //sort.ParentName = "根节点";
            }

            sort.CascadeId = cascadeId;
        }

        #endregion 私有方法



    }
}
